<template>
	<view>
		<view class="bgw">
			<view class="item">
				<view class="flex">
					<view class="flex-1 flex">
						<view class="font-bold">
							{{cus_loc_id_name}}
						</view>
					</view>
					<!-- <view class="" style="width: 20%;">
						<text class="font-24 text-gray">报餐：</text>
						<text class="font-bold">-</text>
					</view> -->
					<view class="text-ellipsis" style="width: 28%;">
						<text class="font-24 text-gray">份数：</text>
						<text class="font-bold">{{sales_qty}}</text>
					</view>
					<view class="text-ellipsis" style="width: 22%;">
						<text class="font-bold">￥{{sales_price | formatPrice}}</text>
					</view>
					<view class="" style="width: 60px">
						<view class="flex" style="justify-content: flex-end;">
							<view class="icon-btn" @click="add" v-if="!readonly">

								<u-icon name="plus" color="#999999" size="14"></u-icon>
							</view>
							<view class="icon-btn ml15" :class="show?'active':''" @click="toggle()">

								<u-icon :name="show?'arrow-up':'arrow-down'" :color="show?'#ffffff':'#999999'"
									size="14"></u-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-show="show">
				<u-line></u-line>
				<view class="item bg-gray">
					<view class="flex font-24 text-light-gray">
						<view class="text-center" style="width: 30%;">
							餐别 [销售类型]
						</view>
						<view class="text-center" style="width: 25%;">
							金额
						</view>
						<view class="text-center flex-1">
							用餐
						</view>
						<view class="text-center flex-1 ml15">
							单价
						</view>
						<view class="ml15" style="width: 22px">
							
						</view>
					</view>
				</view>
				<u-line></u-line>
				<template v-for="(v,i) in detail.childs">
					<view class="item">
						<view class="flex">
							<view class="" style="width: 30%;" v-if="!readonly">
								<picker mode="multiSelector" :range="picker_range" :value="picker_value" @change="bind_picker_change" range-key="name" :data-index="i">
									<view class="flex">
										<view class="flex-1" v-if="v.dinner_type_id.length == 2">
											{{v.dinner_type_id[1]}} [{{v.sales_category_id[1]}}]
										</view>
										<view class="flex-1 text-light-gray" v-else>
											请选择
										</view>
										<view class="ml5">
											<u-icon name="arrow-down" color="#999999" size="14"></u-icon>
										</view>
									</view>
									<!-- <u-button type="info" size="small" text="早餐 [早餐]"></u-button> -->
								</picker>
							</view>
							<view class="" style="width: 30%;" v-else>
								{{v.dinner_type_id[1]}} [{{v.sales_category_id[1]}}]
							</view>
							<view class="text-center text-ellipsis" style="width: 25%;">
								￥{{sales_price_item[i]}}
							</view>
							<view class="text-center flex-1" v-if="!readonly && !isDivision">
									<input v-model="qty[i]" type="number" placeholder="请输入" @blur="qty_blur" :maxlength="6" @input="qty_input" :data-index="i" class="input_border_bottom" :class="errorsQty[i]?'input_border_bottom_red':''"/>
							</view>
							<view class="text-center flex-1" v-if="!readonly && isDivision" @click="openDivision(i)">
								<input v-model="qty[i]" type="number" placeholder="请输入"  class="input_border_bottom" :class="errorsQty[i]?'input_border_bottom_red':''" disabled/>
							</view>
							<view class="text-center flex-1" v-if="readonly && !isDivision">
								{{qty[i]}}
							</view>
							<view class="text-center flex-1" v-if="readonly && isDivision" @click="openDivision(i)">
								{{qty[i]}} (...)
							</view>
							<view class="text-center flex-1 ml15"  v-if="!readonly">
									<input v-model="price[i]" type="digit" placeholder="请输入" @blur="price_blur" @input="price_input" :maxlength="6" :data-index="i" class="input_border_bottom" :class="errorsPrice[i]?'input_border_bottom_red':''"/>
							</view>
							<view class="text-center flex-1 ml15" v-else>
								{{price[i]}}
							</view>
							<view class="ml15" style="width: 22px" >
								<view class="flex" style="justify-content: flex-end;"  v-if="!readonly">
									
									<view class="" v-if="loadingId[v.id]">
										<u-loading-icon size="16"></u-loading-icon>
									</view>
									
									<view class="" v-else>
										<u-icon name="trash" color="#999999" size="16" @click="del(i)"></u-icon>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="flex" style="padding: 0 20upx 10upx 20upx;" v-show="tipsQty[i]">
						<u-icon name="error-circle" color="#999999" size="14"  class="mr10"></u-icon>
						<text class="text-light-gray">{{tipsQty[i]}}</text>
					</view>
					<view class="text-red flex" style="padding: 0 20upx 10upx 20upx;" v-show="errorsQty[i] || errorsPrice[i]">
						<u-icon name="close-circle" color="#D6251F" size="14" class="mr10"></u-icon>
						<text>{{errorsQty[i]}}</text>
						<text v-if="errorsQty[i]">；</text>
						<text>{{errorsPrice[i]}}</text>
					</view>
					<u-line dashed></u-line>
				</template>
			</view>
		</view>

		<view class="blank20"></view>
	</view>
</template>

<script>
	import {
		one_day_kpi_report_detail,
		save_one_day_sales_cost_detail,
		common_write,
		common_create,
		common_delete
	} from '@/common/api.js';
	export default {
		name: "sale-item",
		props: {
			detail: Object,
			open:Boolean,
			date:String,
			readonly:Boolean,
			modelname:String,
			dinners:Array,
			sales:Array,
			cfg:Object,
			division:Array
		},
		data() {
			return {
				// id: this.detail.id,
				show: this.open,
				qty: [],
				errorsQty:[],
				tipsQty:[],
				errorsPrice:[],
				price: [],
				picker_range: [
					this.dinners,
					this.sales
				],
				picker_value: [0, 0],
				loadingId:{},
				cus_loc_id_name:this.detail.childs[0].cus_loc_id[1],
				cus_loc_id:this.detail.childs[0].cus_loc_id[0],
				max_sales_qty:0,
				max_price:0,
				isDivision:this.division.length>1,
				old_sales_price:0,
				old_sales_qty:0,
			};
		},
		watch: {
			open(newVal, oldVal){
				// console.log(newVal);
				this.show = newVal;
			},
			qty:{
				handler(newVal, oldVal) {
					if(this.readonly){
						return;
					}
					newVal.forEach((num,i)=>{
						if((num+'') == ''){
							this.errorsQty[i] = '';
							this.tipsQty[i] = '';
							return;
						}
						let id = this.detail.childs[i].id;
						// console.log(num);
						let re = new RegExp("^[0-9]*[1-9][0-9]*$"); 
						if((num+'').match(re)==null && !this.isVirtualId(id)){
							this.errorsQty[i] = '用餐为大于0的正整数';
						}else if(this.max_sales_qty && Number(num)>this.max_sales_qty){
							this.errorsQty[i] = '用餐不能超过上限'+this.max_sales_qty;
						}else{
							this.errorsQty[i] = '';
						}
						let {dinner_type_id,sales_category_id} = this.detail.childs[i];
						try{
							let cfg = this.cfg[dinner_type_id[0]][sales_category_id[0]];
							let { dinner_qty_upper_limit } = cfg;
							if(Number(num)>dinner_qty_upper_limit && dinner_qty_upper_limit>0){
								this.tipsQty[i] = '用餐超过报警值'+dinner_qty_upper_limit+'，请检查是否正确';
							}else{
								this.tipsQty[i] = ''
							}
						}catch(e){
							this.tipsQty[i] = ''
						}
					})
				},
				immediate: false,
				deep: true
			},
			price:{
				handler(newVal, oldVal) {
					if(this.readonly){
						return;
					}
					newVal.forEach((num,i)=>{
						if((num+'') == ''){
							this.errorsPrice[i] = '';
							return;
						}
						let id = this.detail.childs[i].id;
						if((Number(num)<0 || Number(num) == 0) && !this.isVirtualId(id)){
							this.errorsPrice[i] = '单价不得小于或等于0';
						}else if(this.max_price && Number(num)>this.max_price){
							this.errorsPrice[i] = '单价超过'+this.max_price;
						}else{
							this.errorsPrice[i] = '';
						}
					})
				},
				immediate: false,
				deep: true
			},
		},
		created(){
			let qty = [];
			let price = [];
			let errorsQty = [];
			let tipsQty = [];
			let errorsPrice = [];
			this.detail.childs.forEach((v,i)=>{
				errorsQty.push('');
				tipsQty.push('');
				errorsPrice.push('');
				qty.push(v.sales_qty);
				price.push(v.price);
			})
			this.qty = qty;
			this.price = price;
			this.errorsQty = errorsQty;
			this.tipsQty = tipsQty;
			this.errorsPrice = errorsPrice;
			this.old_sales_price = this.get_sales_price();
			this.old_sales_qty = this.get_sales_qty();
			let userInfo = this.$store.getters.get_userInfo;
			// console.log(userInfo);
			this.max_sales_qty = userInfo['通用配置'].max_sales_qty||0;
			this.max_price = userInfo['通用配置'].max_price||0;
		},
		computed:{
			sales_price(){
				return this.get_sales_price();
			},
			sales_qty(){
				return this.get_sales_qty();
			},
			sales_price_item(){
				let num = [];
				this.qty.forEach((v,i)=>{
					num.push(Number(v)*Number(this.price[i]));
				});
				return num
			}
		},
		filters: {

		},
		methods: {
			get_sales_qty(){
				let num = 0;
				this.qty.forEach(v=>{
					num+= Number(v);
				});
				return num
			},
			get_sales_price(){
				let num = 0;
				this.qty.forEach((v,i)=>{
					num+=(Number(v)*Number(this.price[i]));
				});
				return num
			},
			bind_picker_change(e) {
				let index = e.target.dataset.index;
				let value = e.detail.value;
				let [i1,i2] = value;
				let dinner_type_id = [this.dinners[i1].id,this.dinners[i1].name]
				let dinner_type = this.dinners[i1].dinner_type;
				let sales_category_id = [this.sales[i2].id,this.sales[i2].name];
				
				if(this.detail.childs[index].dinner_type_id[0] == dinner_type_id[0] && this.detail.childs[index].dinner_type == dinner_type && this.detail.childs[index].sales_category_id[0] == sales_category_id[0]){
					//未修改
					return;
				}
				
				let item = this.detail.childs.find(v=>v.dinner_type_id[0] == dinner_type_id[0] && v.sales_category_id[0] == sales_category_id[0]);
				if(item){
					uni.$u.toast('已有'+dinner_type_id[1]+'['+sales_category_id[1]+']，请重新选择');
					return;
				}
				
				
				// console.log(e);
				this.detail.childs[index].dinner_type_id = dinner_type_id;
				this.detail.childs[index].dinner_type = dinner_type;
				this.detail.childs[index].sales_category_id = sales_category_id;
				try{
					let cfg = this.cfg[dinner_type_id[0]][sales_category_id[0]];
					if(!this.price[index]){
						this.price[index] = cfg.price;
					}
				}catch(e){}
				this.save(index);
			},
			qty_change(e) {
				// console.log(e);
			},
			price_change() {

			},
			qty_blur(e){
				// console.log(e);
				let i = e.target.dataset.index;
				if(this.detail.childs[i].sales_qty == Number(this.qty[i])){
					//未修改
					return;
				}
				this.save(i);
			},
			qty_input(e){
				let i = e.target.dataset.index;
				if(this.qty[i]+'' != ''){
					let num = Number(this.qty[i]);
					this.$set(this.qty,i,num);
				}
			},
			openDivision(i){
				let dinner_type_id = this.detail.childs[i].dinner_type_id;
				let sales_category_id = this.detail.childs[i].sales_category_id;
				if(!dinner_type_id[0]){
					uni.$u.toast('请选择餐别');
					return;
				}
				
				let title = this.cus_loc_id_name + ' '+dinner_type_id[1]+'['+sales_category_id[1]+'] 部门用餐';
				let division_qty_json = JSON.parse(JSON.stringify(this.detail.childs[i].division_qty_json)) || {};
				let list = JSON.parse(JSON.stringify(this.division));
				list.forEach(v=>{
					v.sales_qty = division_qty_json[v.id] || '';
				})
				let data = {
					title:title,
					readonly:this.readonly,
					list:list
				};
				let fn = (value)=>{
					let {sales_qty,division_qty_json} = value;
					this.detail.childs[i].division_qty_json = division_qty_json;
					this.$set(this.qty,i,sales_qty);
					this.save(i);
				};
				this.$emit("openDivision",data,fn.bind(this));
			},
			price_blur(e){
				let i = e.target.dataset.index;
				if(this.detail.childs[i].price == Number(this.price[i])){
					//未修改
					return;
				}
				this.save(i);
			},
			price_input(e){
				let i = e.target.dataset.index;
				if(this.price[i]+'' != ''){
					let num = Number(this.price[i]);
					this.$set(this.price,i,num);
				}
			},
			resetItem(i){
				let data = JSON.parse(JSON.stringify(this.detail.childs[i]));
				this.$emit("reset",data);
				this.detail.childs[i] = data;
				this.price[i] = data.price;
				this.qty[i] = data.sales_qty;
			},
			save(i){
				// let checkTimeValue = {};
				// this.$emit("checkTime",checkTimeValue);
				// if(!checkTimeValue.value){
				// 	return;
				// }
				if(this.errorsQty[i]){
					uni.$u.toast('请输入正确的用餐');
					return;
				}
				if(this.errorsPrice[i]){
					uni.$u.toast('请输入正确的单价');
					return;
				}
				let init_data = JSON.parse(JSON.stringify(this.detail.childs[i]));
				let data = JSON.parse(JSON.stringify(this.detail.childs[i]));
				// console.log(data);
				data.cus_loc_id = data.cus_loc_id[0];
				data.dinner_type_id = data.dinner_type_id[0];
				data.sales_category_id = data.sales_category_id[0];
				init_data.price = data.price = Number(this.price[i]);
				init_data.sales_qty = data.sales_qty = Number(this.qty[i]);
				if(!data.dinner_type_id){
					uni.$u.toast('请选择餐别');
					return;
				}
				if(!data.sales_qty){
					uni.$u.toast('请输入用餐');
					return;
				}
				if(!data.price){
					uni.$u.toast('请输入单价');
					return;
				}
				this.$set(this.loadingId,data.id, true);
				let isVirtualId = this.isVirtualId(data.id);
				if(isVirtualId){
					data.date = this.date;
					common_create({
						model_name:this.modelname,//'sales_record',
						vals_list:[data]
					},{custom:{catch:true}}).then((res) => {
						let newId = res.result[data.id].id;
						this.detail.childs[i].sales_qty = data.sales_qty;
						this.detail.childs[i].price = data.price;
						this.detail.childs[i].id = newId;
						let diff = this.sales_price - this.old_sales_price;
						let diffQty = this.sales_qty - this.old_sales_qty;
						// console.log(this.sales_qty);
						// console.log(this.old_sales_qty);
						this.$emit("updata",init_data,newId,diff,diffQty);
						this.old_sales_price = this.get_sales_price();
						this.old_sales_qty = this.get_sales_qty();
					}).catch((res) => {
						this.resetItem(i);
					}).finally(() => {
						// console.log('finally');
						setTimeout(()=>{
							this.$set(this.loadingId,data.id, false)
						},500)
					})
				}else{
					common_write({
						model_name:this.modelname,
						vals_list:[data]
					},{custom:{catch:true}}).then((res) => {
						let diff = this.sales_price - this.old_sales_price;
						let diffQty = this.sales_qty - this.old_sales_qty;
						this.$emit("updata",init_data,0,diff,diffQty);
						this.old_sales_price = this.get_sales_price();
						this.old_sales_qty = this.get_sales_qty();
					}).catch(() => {
						this.resetItem(i);
					}).finally(() => {
						setTimeout(()=>{
							this.$set(this.loadingId,data.id, false)
						},500)
					})
				}
			},
			add(){
				let data = {
					cus_loc_id:[this.cus_loc_id,this.cus_loc_id_name]
				};
				this.$emit("add",data);
				let _length = this.detail.childs.push(data);
				this.errorsQty.push('');
				this.tipsQty.push('');
				this.errorsPrice.push('');
				this.price.push('');
				this.qty.push('');
				this.show = true;
				// console.log(data);
			},
			del(index){
				let data  = this.detail.childs[index];
				if(this.isVirtualId(data.id)){
					this.remove(index);
					return;
				}
				let name = data.dinner_type_id[1] + '[' + data.sales_category_id[1] +']';
				this.$store.dispatch('modal', '确认删除 '+name+'？').then(() => {
					this.$set(this.loadingId,data.id, true)
					common_delete({
						model_name:this.modelname,
						ids:[data.id]
					},{custom:{catch:true}}).then((res) => {
						this.remove(index);
					}).catch(() => {
					
					}).finally(() => {
						setTimeout(()=>{
							this.$set(this.loadingId,data.id, false)
						},500)
					})
				})
				
			},
			remove(index){
				this.detail.childs = this.detail.childs.filter((v,i)=>i != index);
				this.price = this.price.filter((v,i)=>i != index);
				this.qty = this.qty.filter((v,i)=>i != index);
				this.errorsQty = this.errorsQty.filter((v,i)=>i != index);
				this.errorsPrice = this.errorsPrice.filter((v,i)=>i != index);
				this.tipsQty = this.tipsQty.filter((v,i)=>i != index);
				let diff = this.sales_price - this.old_sales_price;
				let diffQty = this.sales_qty - this.old_sales_qty;
				this.$emit("updata",0,0,diff,diffQty);
				this.old_sales_price = this.get_sales_price();
				this.old_sales_qty = this.get_sales_qty();
			},

			toggle(time_i) {
				this.show = !this.show;
				// this.$forceUpdate();
			},
		}

	}
</script>

<style>

</style>